package blog.web;

import java.util.Collection;
import java.util.Date;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import blog.model.User;
import blog.service.UserService;

@Controller
public class UserController {
	
	@Autowired private UserService userService;

	@RequestMapping(value = "/login", method = RequestMethod.GET)
    public void login() {
	}

	@RequestMapping(value = "/register", method = RequestMethod.GET)
    public void register(Model model) {
		model.addAttribute("user", new User());
	}
	
	@RequestMapping(value = "/login", method = RequestMethod.POST)
    public String auth(User user, HttpSession session) {
		System.out.println("test");
		String email = user.getEmail();
		String password= user.getPassword();
		System.out.println(user);
        if(user.getEmail() != null && user.getPassword()!= null){
            if( userService.checkUserLogin(email, password) ){
            	session.setAttribute("user", user);
                return "redirect:findBlogs.do";
            }else{
                return "redirect:login.do";
            }
        }else{
            return "redirect:login.failed";
        }   
    }

	@RequestMapping(value = "/findUsers", method = RequestMethod.GET)
	public Collection<User> findUsersHandler() {
		return userService.findUsers();
	}

	@RequestMapping(value= "/editUser", method = RequestMethod.GET)
	public User editUserHandler(@RequestParam("userId") int userId) {
		return userService.findUser(userId); 
	}
	
	@RequestMapping(value= "/saveUser", method = RequestMethod.POST)
	public String saveUserHandler(User user, HttpSession session) {
		userService.createUser(user);
		session.setAttribute("user", user);
		return "redirect:findBlogs.do";
	}
	
	@RequestMapping(value= "/updateUser", method = RequestMethod.POST)
	public String updateUserHandler(User user) {
		user.setRegDate(new Date());
		userService.updateUser(user);
		return "redirect:findUsers.do";
	}
	
	@RequestMapping(value= "/createUser", method = RequestMethod.GET)
	public void createUserHandler(Model model) {
		model.addAttribute("user", new User(new Date()));
	}
	
}
